package com.ggh.jinjilive.ui.mine.personal;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.ggh.jinjilive.BaseApplication;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.databinding.ActivityPersonalDataBinding;
import com.ggh.jinjilive.mobile.mine.personal.PersonalDataMobile;
import com.ggh.jinjilive.mobile.mine.video.PersonalVideoList;
import com.ggh.jinjilive.mobile.social.near.NearUser;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.ui.mine.personal.adapter.PersonalDataAdapter;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.ggh.jinjilive.utils.loginIMUtils;
import com.ggh.jinjilive.views.DividerItemDecoration;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tencent.imsdk.v2.V2TIMFriendInfo;
import com.tencent.imsdk.v2.V2TIMFriendOperationResult;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.BlurTransformation;


@Route(path = ARouterUtils.PersonalDataActivity)
public class PersonalDataActivity extends BaseActivity<ActivityPersonalDataBinding> implements OnRefreshListener, OnLoadMoreListener, View.OnClickListener {
    //VM
    private PersonalDataViewModel personalDataViewModel;
    //传输过来的数据
    private NearUser nearUser;
    //是否拉黑
    private boolean inBlackList = false;

    //视频适配器
    private PersonalDataAdapter personalDataAdapter;
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).statusBarDarkFont(true).navigationBarColor(R.color.white).navigationBarDarkIcon(true).init();
        BaseApplication.getInstance().getAppComponent().doInjectionMain(this);
        personalDataViewModel = new ViewModelProvider(this,viewModelFactory).get(PersonalDataViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_personal_data;
    }

    @Override
    public void initParam() {
        super.initParam();
        nearUser = (NearUser) getIntent().getSerializableExtra("nearUser");
    }


    @Override
    public void initView() {
        super.initView();
        //获取状态栏高度
        binding.llSpacing.setPadding(0, BarUtils.getStatusBarHeight(),0,0);

        //屏幕高度
        ViewGroup.LayoutParams params =  binding.appBarLayout.getLayoutParams();
        params.height = ScreenUtils.getScreenHeight() / 3;
        binding.appBarLayout.setLayoutParams(params);
        //刷新控件
        binding.refreshLayout.setRefreshHeader(new MaterialHeader(mContext));
        binding.refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        binding.refreshLayout.autoRefresh();
        //视频适配器
        personalDataAdapter = new PersonalDataAdapter(mContext);
        GridLayoutManager mCommodityManager = new GridLayoutManager(mContext, 2);
        mCommodityManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if(position == 0){
                    return 2;
                }
                return 1;
            }
        });
        binding.rv.setLayoutManager(mCommodityManager);
        binding.rv.addItemDecoration(new DividerItemDecoration(mContext));
        binding.rv.setAdapter(personalDataAdapter);
    }

    @Override
    public void initData() {
        super.initData();
        //根据个人信息获取个人资料
        personalDataViewModel.videoAnchorView(nearUser.getId());
        //获取当前用户发布的视频
        personalDataViewModel.isRefresh = true;
        personalDataViewModel.infoVideoList(nearUser.getId());
        //获取黑名单列表
        getBlackList();

    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //刷新
        binding.refreshLayout.setOnRefreshListener(this);
        //加载
        binding.refreshLayout.setOnLoadMoreListener(this);
        //返回按键
        binding.llReturn.setOnClickListener(this);
        //关注
        binding.ButtonAttention.setOnClickListener(this);
        //拉黑
        binding.ButtonShielding.setOnClickListener(this);
        //根据个人信息获取个人资料
        personalDataViewModel.mPersonalDataMobile.observe(this, new Observer<PersonalDataMobile>() {
            @Override
            public void onChanged(PersonalDataMobile personalDataMobile) {
                cancelDialog();
                //个人资料
                setPersonalData(personalDataMobile);
            }
        });
        //获取当前用户发布的视频
        personalDataViewModel.mPersonalVideoList.observe(this, new Observer<List<PersonalVideoList>>() {
            @Override
            public void onChanged(List<PersonalVideoList> personalVideoLists) {
                binding.refreshLayout.finishRefresh();
                if(null != personalVideoLists){
                    if(personalDataViewModel.isRefresh){
                        binding.refreshLayout.finishLoadMore();
                        personalVideoLists.add(0,null);
                        personalDataAdapter.addCustomMessage(personalVideoLists);
                    }else {
                        if(personalVideoLists.size() > 0){
                            personalDataAdapter.setList(personalVideoLists);
                            binding.refreshLayout.finishLoadMore();
                        }else {
                            binding.refreshLayout.finishLoadMoreWithNoMoreData();
                        }
                    }
                }else {
                    binding.refreshLayout.finishLoadMore();
                }
            }
        });
    }


    @Override
    public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
        personalDataViewModel.isRefresh = true;
        personalDataViewModel.infoVideoList(nearUser.getId());
    }

    @Override
    public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
        personalDataViewModel.isRefresh = false;
        personalDataViewModel.infoVideoList(nearUser.getId());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.Button_attention://关注
                showDialog();
                //关注
                personalDataViewModel.myFollow(nearUser.getId());
                break;
            case R.id.Button_shielding://拉黑
                List<String> stringList = new ArrayList<>();
                stringList.add(nearUser.getId() +"");
                if (inBlackList){
                    // 把用户从黑名单中删除
                    loginIMUtils.deleteFromBlackList(stringList, new V2TIMValueCallback<List<V2TIMFriendOperationResult>>() {
                        @Override
                        public void onSuccess(List<V2TIMFriendOperationResult> v2TIMFriendOperationResults) {
                            //获取黑名单列表
                            getBlackList();
                        }

                        @Override
                        public void onError(int code, String desc) {

                        }
                    });
                }else {
                    //屏蔽某人的消息（添加该用户到黑名单中）
                    loginIMUtils.addToBlackList(stringList, new V2TIMValueCallback<List<V2TIMFriendOperationResult>>() {
                        @Override
                        public void onSuccess(List<V2TIMFriendOperationResult> v2TIMFriendOperationResults) {
                            //获取黑名单列表
                            getBlackList();
                        }

                        @Override
                        public void onError(int code, String desc) {

                        }
                    });
                }
                break;
        }
    }


    /**
     * 个人资料
     * @param personalDataMobile
     */
    public void setPersonalData(PersonalDataMobile personalDataMobile){
        if(null != personalDataMobile){
            //背景
            Glide.with(this).load(personalDataMobile.getHead_portrait()).apply(RequestOptions.bitmapTransform(new BlurTransformation(30))).into(binding.bgImg);
            //装扮
            Glide.with(binding.imgDressUp).load(personalDataMobile.getHead_frame()).into(binding.imgDressUp);
            //头像
            Glide.with(binding.riv).load(personalDataMobile.getHead_portrait()).into(binding.riv);
            //名称
            binding.userName.setText(personalDataMobile.getNickname());
            //性别
            if (personalDataMobile.getSex() == 1){
                binding.sexIcon.setImageResource(R.mipmap.ic_male);
            }else if(personalDataMobile.getSex() == 2){
                binding.sexIcon.setImageResource(R.mipmap.ic_female);
            }
            //级别
            binding.userLevel.setText(personalDataMobile.getLevel());
            //级别图片
            Glide.with(binding.levelImg).load(personalDataMobile.getLevel_img()).into(binding.levelImg);
            //用户ID
            binding.userIdText.setText("ID:" + personalDataMobile.getAnchor_id());
            //粉丝
            binding.fansNum.setText(personalDataMobile.getFans_num() + "粉丝");
            //关注
            binding.followedNum.setText(personalDataMobile.getFocus_num() + "关注");
            //是否关注
            if(personalDataMobile.getIs_follow() == 1){
                binding.ButtonAttention.setText("+关注");
                binding.ButtonAttention.setTextColor(Color.parseColor("#7EBFFF"));
            }else {
                binding.ButtonAttention.setText("已关注");
                binding.ButtonAttention.setTextColor(Color.parseColor("#a1a1a1"));
            }
        }

    }

    /**
     * 获取黑名单列表
     */
    public void getBlackList(){
        //获取黑名单列表
        loginIMUtils.getBlackList(new V2TIMValueCallback<List<V2TIMFriendInfo>>() {
            @Override
            public void onSuccess(List<V2TIMFriendInfo> v2TIMFriendInfos) {
                inBlackList = false;
                for (int i = 0; i < v2TIMFriendInfos.size(); i ++){
                    if (v2TIMFriendInfos.get(i).getUserID().equals(String.valueOf(nearUser.getId()))){
                        inBlackList = true;
                    }
                }
                if (inBlackList){
                    if(null != binding.ButtonShielding){
                        binding.ButtonShielding.setText("已拉黑");
                        binding.ButtonShielding.setTextColor(Color.parseColor("#a1a1a1"));
                    }
                }else{
                    if(null != binding.ButtonShielding){
                        binding.ButtonShielding.setText("拉黑");
                        binding.ButtonShielding.setTextColor(Color.parseColor("#000000"));
                    }
                }
            }

            @Override
            public void onError(int code, String desc) {

            }
        });
    }
}
